import { useLayoutEffect, useRef } from 'react';
import mhtml2html from './mhtml2html.js';
import type { CSSProperties } from 'react';

export type PreviewMhtmlProps = {
	/**
	 * 文件在服务器的路径，需要携带明确后缀
	 * 示例：/test/to/xxx.mhtml
	 */
	path: string;
	/** 添加在最外层的 className */
	rootClassName?: string;
	/** 添加在最外层的 style */
	rootStyle?: CSSProperties;
	/** 外层容器宽度 */
	width?: CSSProperties['width'];
	/** 外层容器高度 */
	height?: CSSProperties['height'];
};

// 去除传递前缀时带有的'/'
export const trimSlashes = (str: string) =>
	`${str
		.split('/')
		.filter((v) => v !== '')
		.join('/')}`;

const PreviewMhtml = (props: PreviewMhtmlProps) => {
	const { path, rootClassName, rootStyle, width = '100%', height = '100%' } = props;

	const iframeRef = useRef<HTMLIFrameElement>();

	const createPreviewDom = async () => {
		const url = 'http://dev-host/minio-file/' + trimSlashes(path);
		const response = await fetch(url);
		const blob = await response.blob();

		const ext = url.split('.').pop();
		const {
			contentWindow: { document }
		} = iframeRef.current;
		const head = document.head;
		const body = document.body;

		const fileReader = new FileReader();
		fileReader.onload = (event) => {
			if (ext === 'mhtml') {
				const fileContent = event.target.result;
				const res = mhtml2html.convert(fileContent);
				const doc = res.window.document;
				iframeRef.current.innerHTML = doc.head.innerHTML + doc.body.innerHTML;

				head.innerHTML = doc.head.innerHTML;
				body.innerHTML = doc.body.innerHTML;
			} else {
				const fileContent = event.target.result;
				document.write(fileContent as string);
			}
		};
		fileReader.readAsText(blob);
	};
	useLayoutEffect(() => {
		const {
			contentWindow: { document }
		} = iframeRef.current;
		const head = document.head;
		const body = document.body;
		head.innerHTML = '';
		body.innerHTML = '';
		if (path) createPreviewDom();
	}, [path]);

	return (
		<div className={rootClassName} style={{ width, height, ...rootStyle }}>
			<iframe ref={iframeRef} style={{ border: 'none', width: '100%', height: '100%' }} />
		</div>
	);
};

export default PreviewMhtml;
